package com.example.mywood;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.share.Sharer;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.widget.ShareDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import adapter.HorImageAdapter;
import bean.ContentDataBean;
import bean.GuigeDataBean;
import myapp.MyApp;
import myview.CustomProgressDialog;
import myview.CustomTextView;
import myview.HorizontalListView;
import util.DensityUtil;
import util.GlideUtils;
import util.MyLog;
import util.OrderEventMessage;
import util.RequestManager;
import util.ShareUtil;
import util.SystemStatusManager;
import util.ZoomImageview;
import util.utils;

public class ShowRoomActivity extends BaseActivity {


    private Context context;
    private MyApp myapp;
    private LayoutInflater mInflater;
    private String goodsid;
    private int width;
    private int heightPixels;
    private String token;
    private ImageView img_bigimg;
    private LinearLayout ll_reback;
    private List<String> imglist = new ArrayList<>();
    private String imagebig;
    private String store_name;
    private String store_info;
    private String price;
    private String status;
    private String msgstr;
    private String collection = "0";
    private CallbackManager callbackManager;
    private ShareDialog shareDialog;
    private PopupWindow mPopupWindow;
    private String urlstr;
    private String domain;
    private Bitmap thumb = null;
    private String apptype = "";
    private String textData;
    private ContentDataBean.DataBean textContent;
    private LinearLayout ll_guige;
    private List<GuigeDataBean> guigelists = new ArrayList<>();
    private SharedPreferences sharedPreferences;
    private CustomProgressDialog customProgressDialog;
    private TextView tv_titlename;
    private TextView tv_zhanting_name;
    private TextView tv_content;
    private TextView tv_opentime;
    private LinearLayout ll_location;
    private TextView tv_location;
    private TextView tv_time;
    private TextView tv_goods_link;
    private LinearLayout ll_zhantinggoods;
    private String nameStr;
    private String phoneStr;
    private String imageStr;
    private String end_timeStr;
    private String contentStr;
    private String start_timeStr;
    private String locationStr;
    private String introduce;
    private PackageManager mPackageManager;
    private static List<String> mPackageNames = new ArrayList<>();
    private static final String GAODE_PACKAGE_NAME = "com.autonavi.minimap";
    private String url;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_showroom);
        context = this;
        myapp = (MyApp) getApplicationContext();
//        hideBottomUIMenu();
        EventBus.getDefault().register(this);
        sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        apptype = sharedPreferences.getString("apptype", "0");
        domain = sharedPreferences.getString("domain", "");
        urlstr = sharedPreferences.getString("urlstr", "");
        textData = sharedPreferences.getString("textData", "");
        mInflater = LayoutInflater.from(context);
        goodsid = getIntent().getStringExtra("goodsid");
        MyLog.e("1111111111", "111111111 " + goodsid);
        textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {
        }.getType());

        customProgressDialog = new CustomProgressDialog(context, "", R.style.CommProgressDialog);
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount=0f;   //取值为0-1之间  1是全黑
//		params.width = 180;//设置进度条的宽度
//		params.height = 180;//设置进度条的宽度
        customProgressDialog.getWindow().setAttributes(params);

        setTranslucentStatus();
        getScreenDen();
        initView();
        initData();
        initLin();
        getZhantingData();

    }

    @Subscribe
    public void onEventMainThread(OrderEventMessage event) {
        String message = event.getMessage();
        Log.e("message--new--order", message);
       /* if ("图片双击事件".equals(message)) {
            //TODO   显示大图
            String type = event.getType();
            Log.e("eventbus接收数据成功", type + "     ------");
            GlideUtils.loadImagedefault(context, imglist.get(Integer.parseInt(type)), img_bigimg);
//            showBigImage(type);
            ArrayList<String> ss = new ArrayList<>();
            for (int m = 0;m<imglist.size();m++){
                ss.add(imglist.get(m));
            }

            Intent intent = new Intent(context, ImageActivity.class);
            intent.putExtra("position",type);
            intent.putExtra("imgs",ss);
            context.startActivity(intent);
        }*/

    }

    private void initView() {
        ll_reback = findViewById(R.id.ll_reback);
        img_bigimg = findViewById(R.id.img_bigimg);
        tv_titlename = findViewById(R.id.tv_titlename);
        tv_zhanting_name = findViewById(R.id.tv_zhanting_name);
        tv_content = findViewById(R.id.tv_content);
        tv_opentime = findViewById(R.id.tv_opentime);
        ll_location = findViewById(R.id.ll_location);
        tv_location = findViewById(R.id.tv_location);
        tv_time = findViewById(R.id.tv_time);
        tv_goods_link = findViewById(R.id.tv_goods_link);
        ll_zhantinggoods = findViewById(R.id.ll_zhantinggoods);
        ContentDataBean.DataBean textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {
        }.getType());
        if (textContent != null) {
            tv_titlename.setText(textContent.getShowroom());
            tv_opentime.setText(textContent.getBusiness_hours());
            tv_goods_link.setText(textContent.getRecome_good_link());
        }

    }

    private void initData() {

    }

    private String imgUrl = "";
    private int itemplag = 0;
    @SuppressLint("ClickableViewAccessibility")
    private void initLin() {

        ll_reback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        img_bigimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                showBigImage(imgUrl);
                ArrayList<String> ss = new ArrayList<>();
                for (int m = 0;m<imglist.size();m++){
                    ss.add(imglist.get(m));
                }

                Intent intent = new Intent(context, ImageActivity.class);
                intent.putExtra("position",itemplag+"");
                intent.putExtra("imgs",ss);
                context.startActivity(intent);


            }
        });
        ll_zhantinggoods.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(context, ZhantingGoodsActivity.class);
                intent.putExtra("ztname",nameStr);
                startActivity(intent);
            }
        });
        ll_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(haveGaodeMap()){//如果安装高德APP
                    openGaodeMapToGuide();//打开高德APP
                } else {//否则 打开浏览器
                    openBrowserToGuide();
                }
            }
        });

        /*tv_location.setOnTouchListener(new View.OnTouchListener() {
            int firClick = 0;
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if(MotionEvent.ACTION_DOWN == motionEvent.getAction()){

                        firClick = (int) System.currentTimeMillis();

                }else if (MotionEvent.ACTION_UP == motionEvent.getAction()){
                    int timeup = (int) System.currentTimeMillis();
                    if (timeup-firClick > 1000){
                        //长按事件
                        Log.e("长按事件","长按事件");
                    }else{
                        //点击事件
                        Log.e("点击事件","点击事件");
                    }

                }
                return true;
            }
        });*/


    }

    /**
     * 请求头部筛选标题
     */
    private void getZhantingData() {
        String url = myapp.getWebConfig() + "/api/index/gallery_detail";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("gallery_id", goodsid);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                    nameStr = data.getString("name");
                    phoneStr = data.getString("phone");
                    imageStr = data.getString("image");
                    start_timeStr = data.getString("start_time");
                    end_timeStr = data.getString("end_time");
                    contentStr = data.getString("content");
                    locationStr = data.getString("location");
                    introduce = data.getString("introduce");


                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }



    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    String str = (String) msg.obj;
                    Toast.makeText(context, str, Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    if (textContent != null) {
                        Toast.makeText(context, textContent.getNet_error(), Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(context, textContent.getNet_error(), Toast.LENGTH_LONG).show();
                    }
                    break;
                case 2:
                    break;
                case 3:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    tv_zhanting_name.setText(nameStr);
                    tv_time.setText(start_timeStr+"-"+end_timeStr);
                    tv_location.setText(locationStr);
//                    tv_content.setText(contentStr);

                    tv_content.setText(introduce);

                    if (!"".equals(imageStr)){
                        img_bigimg.setVisibility(View.VISIBLE);
                        GlideUtils.loadRoundCircleImage(context,imageStr,img_bigimg);
                    }else{
                        img_bigimg.setVisibility(View.GONE);
                    }
                    imglist.add(imageStr);
                    break;
                case 4:



                    break;
                case 11:
                    if (!islogin) {
                        islogin = true;
                        sharedPreferences.edit().putString("token", "").commit();
                        Intent intent = new Intent(context, LoginActivity.class);
                        context.startActivity(intent);
                        myapp.destoryActivity("主页面");
                    }
                    break;
            }
        }
    };
    private boolean islogin = false;

    /**
     * 设置状态栏背景状态
     */
    public void setTranslucentStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window win = getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
        }
        SystemStatusManager tintManager = new SystemStatusManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(0);//状态栏无背景
    }

    /**
     * 获取屏幕宽度
     */
    private void getScreenDen() {

        WindowManager manager = getWindowManager();
        DisplayMetrics dm = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        //以要素为单位
        width = dm.widthPixels;
        heightPixels = dm.heightPixels;
        MyLog.e("获取屏幕高度", heightPixels + "    高度");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }





    private void showBigImage(String url) {
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View popupWindow = layoutInflater.inflate(R.layout.popup_bigimage, null);
        ZoomImageview iv_zoom = popupWindow.findViewById(R.id.iv_zoom);
        ImageView img_close = popupWindow.findViewById(R.id.img_close);
        img_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mPopupWindow != null) {
                    mPopupWindow.dismiss();
                }
            }
        });
        Glide.with(this).load(url).into(iv_zoom);

        int mScreenWidth = getWindowManager().getDefaultDisplay().getWidth();
        mPopupWindow = new PopupWindow(popupWindow, ActionBar.LayoutParams.MATCH_PARENT,
                ActionBar.LayoutParams.MATCH_PARENT);
        mScreenWidth = getWindowManager().getDefaultDisplay().getHeight();
        int mPopupWindowWidth = mPopupWindow.getWidth();
        int mPopupWindowHeight = mPopupWindow.getHeight();
        // 需要设置一下此参数，点击外边可消失
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setFocusable(true); // pop 显示时， 不让外部 view 响应点击事件
        //防止被底部虚拟键挡住
        mPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (Build.VERSION.SDK_INT >= 24) { // Android 7.x中,PopupWindow高度为match_parent时,会出现兼容性问题,需要处理兼容性
            int offsetY = DensityUtil.dip2px(context, utils.getNavigationBarHeight(context));
            if (Build.VERSION.SDK_INT >= 25) { // Android 7.1中，PopupWindow高度为 match_parent 时，会占据整个屏幕
                //故而需要在 Android 7.1上再做特殊处理
                int screenHeight = heightPixels; // 获取屏幕高度
//                int screenHeight = DisplayUtil.getScreenHeight(MainActivity.this); // 获取屏幕高度
                // 设置SelectPicPopupWindow弹出窗体的高
                mPopupWindow.setHeight(screenHeight); // 重新设置 PopupWindow 的高度
//                mPopupWindow.setHeight(screenHeight - utils.getNavigationBarHeight(context)); // 重新设置 PopupWindow 的高度
            }
            mPopupWindow.showAtLocation(img_bigimg,
                    Gravity.BOTTOM,
                    0,
                    0);
            MyLog.e("底部导航栏高度", utils.getNavigationBarHeight(context) + "    gaodu");

        } else {
            mPopupWindow.showAtLocation(img_bigimg,
                    Gravity.BOTTOM,
                    0,
                    0);
//            mPopupWindow.showAsDropDown(img_collect);
        }

        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });

    }

    Bitmap bitmap = null;

    public void returnBitMap(final String url) {

        new Thread(new Runnable() {
            @Override
            public void run() {

                URL myFileUrl = null;

                try {
                    myFileUrl = new URL(url);
                } catch (MalformedURLException e) {
                    return;
                }
                HttpURLConnection conn = null;
                try {
                    conn = (HttpURLConnection) myFileUrl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    int responseCode = conn.getResponseCode();
                    if (responseCode == 200) {
                        InputStream is = conn.getInputStream();
                        conn.setReadTimeout(3000);
                        conn.setConnectTimeout(3000);
                        bitmap = BitmapFactory.decodeStream(is);
                        is.close();
                        conn.disconnect();
                        int width = bitmap.getWidth();
                        int height = bitmap.getHeight();
                        int newWidth = 100;
                        int newHeight = 100;
                        float scaleWidth = ((float) newWidth) / width;
                        float scaleHeight = ((float) newHeight) / height;
                        Matrix matrix = new Matrix();
                        matrix.postScale(scaleWidth, scaleHeight);
                        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
            }
        }).start();
    }

    protected void hideBottomUIMenu() {
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    /**
     * 判断有无安装高德
     * @return
     */
    public boolean haveGaodeMap(){
        initPackageManager();
        return mPackageNames.contains(GAODE_PACKAGE_NAME);
    }
    public void initPackageManager(){
        mPackageManager = context.getPackageManager();
        List<PackageInfo> packageInfos = mPackageManager.getInstalledPackages(0);
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                mPackageNames.add(packageInfos.get(i).packageName);
            }
        }
    }
    private double currLocationX = 0.0;
    private double currLocationY = 0.0;
    /**
     * 打开高德地图
     * https://lbs.amap.com/api/amap-mobile/guide/android/route
     */
    private void openGaodeMapToGuide() {
        try {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            MyLog.i("高德定位：","经度："+currLocationY+" ,纬度："+currLocationX);
            if (currLocationX == 0.0 || currLocationY == 0.0){
                url = "androidamap://route?sourceApplication=amap"+"&dname="+locationStr+"&dev=0&t=1";
            }else {
                url = "androidamap://route?sourceApplication=amap&"
                        +"&dname="+locationStr+"&dev=0&t=1";
            }



            Uri uri = Uri.parse(url);
            //将功能Scheme以URI的方式传入data
            intent.setData(uri);
            //启动该页面即可
            startActivity(intent);

        }catch (Exception e){
            openBrowserToGuide();
        }
    }


    /**
     * 打开浏览器
     */
    private void openBrowserToGuide() {
        String url = "http://uri.amap.com/navigation?to=" +
                locationStr + "&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=0";
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }


}
